var hours = ['8', '9', '10', '11', '12', '13', '14', '15', '16', '17',
             '18', '19', '20'];
var mins = ['00', '30'];
var days = ['M', 'T', 'W', 'R', 'F'];

function render_grid(container) {
  var table = $('<table>').addClass("timegrid");
  var tr = $('<tr>');
  tr.append($('<th>'));
  for(var d in days)
    tr.append($('<th>').html(days[d]));

  table.append(tr);
  for(var h in hours) {
    h = hours[h];
    for(var m in mins) {
      m = mins[m];
      tr = $('<tr>');
      tr.append($('<td>').html(h + ":" + m));
      for(var d in days) {
        d = days[d];
        var td = $('<td>')
          .addClass("timeslot")
          .addClass('day_' + d).addClass('time_' + h + m);
        tr.append(td);
      }
      table.append(tr);
    }
  }
  $(container).append(table);
}

/* Assume 30 min timeslots */
function overlapping_interval(result, d, h, m) {
  var btime = parseInt(h) * 60 + parseInt(m);
  var etime = btime + 30;
  for(var x in result[d]) {
    x = result[d][x];
    var s1 = x.btimemin;
    var s2 = x.etimemin;
    var t1 = btime;
    var t2 = etime;
    if((s1 <= t1 && t1 < s2) || (s1 < t2 && t2 <= s2)) {
      return x;
    }
  }
  return null;
}

function paint_available(elem, interval) {
  var x = (interval ? interval.fraction : 0);
  var c = (interval ? interval.count : "");
  var r = (interval ? interval.locations : null);
  if(! elem.hasClass('occupied')) {
    $(elem)
      .html(c)
      .css({
        'background': 'RGBA(0,0,255,'+x+')',
        'cursor': 'pointer'
      })
      .data('locations', r);
  } else {
    ;
  }
}

function paint_occupied(elem, interval) {
  var code = interval.code;
  $(elem)
    .addClass("occupied")
    .css('background', 'RGBA(255,0,0,0.3)')
    .html(code) ;
}

/* Apply some intervals (result) to the grid using
   the callback */
function overlay_grid(result, callback) {
  if(result.error) {
    $(".timegrid .timeslot").css({
        'background': '#555'
    });
  } else {
    for(var h in hours) {
      h = hours[h];
      for(var m in mins) {
        m = mins[m];
        for(var d in days) {
          d = days[d];
          var selector = ".day_" + d + ".time_" + h + m;
          var x = overlapping_interval(result, d, h, m);
          if(x) callback($(selector), x);
        }
      }
    }
  }
}
